<template>
  <el-dialog v-model="visible" title="修改密码" width="400px" @close="resetForm">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="90px">
      <el-form-item label="原密码" prop="oldPwd">
        <el-input v-model="form.oldPwd" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="新密码" prop="newPwd">
        <el-input v-model="form.newPwd" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmPwd">
        <el-input v-model="form.confirmPwd" type="password" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="onSubmit" :loading="loading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineExpose } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../stores/user'
import { authApi } from '../api/auth'
import { useRouter } from 'vue-router'

const visible = ref(false)
const loading = ref(false)
const formRef = ref()
const form = ref({
  oldPwd: '',
  newPwd: '',
  confirmPwd: ''
})

const rules = {
  oldPwd: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  newPwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '新密码至少6位', trigger: 'blur' }
  ],
  confirmPwd: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== form.value.newPwd) {
          callback(new Error('两次输入的新密码不一致'))
        } else {
          callback()
        }
      }, trigger: 'blur'
    }
  ]
}

const userStore = useUserStore()
const router = useRouter()

function open() {
  visible.value = true
}
function resetForm() {
  form.value.oldPwd = ''
  form.value.newPwd = ''
  form.value.confirmPwd = ''
  loading.value = false
}
async function onSubmit() {
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    loading.value = true
    try {
      const res = await authApi.changePassword(userStore.userId, {
        oldPwd: form.value.oldPwd,
        newPwd: form.value.newPwd
      })
      if (res.data.code === 1000) {
        ElMessage.success('密码修改成功，请重新登录')
        userStore.logout()
        visible.value = false
        router.push('/auth')
      } else {
        ElMessage.error(res.data.msg || '修改失败')
      }
    } catch (e) {
      ElMessage.error(e?.response?.data?.message || '修改失败')
    } finally {
      loading.value = false
    }
  })
}

defineExpose({ open })
</script> 